// 计划页面：新增/编辑弹窗

import React from "react";
import {Button, Col, Form, Input, message, Modal, Row} from "antd";
import {
    ButtonLock,
    SelectJhAccount,
    SelectState2,
} from "../../components/BaseComponent/forms";
import {jhApi} from "../../services/basic";
import moment from "moment";

class AddOrEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            title: "计划-详情"
        }
    }

    dataFormLabel = {}

    showModal = (handler, record) => {
        let title = "计划-详情";
        if (handler === "view") {
            title = "计划-详情";
        } else if (handler === "update") {
            title = "计划-编辑";
        } else if (handler === "create") {
            title = "计划-新增";
        }

        if (this.form) this.form.resetFields();
        this.id = handler === "create"? null:record.id;
        this.setState({
            handler,
            title,
            visible: true
        }, () => {
            this.dateInit();
            if (["view", "update"].includes(handler)) {
                jhApi.getJhById(record.id).then(res => {
                    if (res.code === "1") {
                        const {jhid, jhmc, zhid, ztbz} = res.data
                        this.form.setFieldsValue({jhid, jhmc, zhid, ztbz: ~~ztbz})
                    }
                })
            }
        })
    }

    handleOk = () => {
        const api = this.state.handler === "create" ? jhApi.createJh : jhApi.updateJh;
        return new Promise((resolve, reject) => {
            this.form.validateFields().then(data => {
                api({
                    ...data,
                    id: this.id
                }).then(res => {
                    if (res.code !== "1") {
                        reject();
                        return
                    }
                    message.success('操作成功');
                    this.props.editItemDone();// 刷新
                    this.setState({
                        visible: false
                    }, () => {
                        resolve();
                    })
                }).catch(() => {
                    this.props.editItemDone();// 刷新
                    reject()
                })
            }).catch(e => {
                // 表单校验失败
                console.log(e.errorFields)
                reject();
            })
        })

    }

    handleCancel = () => {
        this.setState({
            visible: false
        })
    }

    dateInit = () => {
        const today = moment(new Date(), "YYYY-MM-DD");
        if (this.form) this.form.setFieldsValue({
            rq: today
        })
    }

    onFormChange = (data, e) => {
        const key = Object.keys(data)[0];
        const label = e ? e.children : null;
        this.dataFormLabel = {
            ...this.dataFormLabel,
            [key]: label
        }
    }

    idBlur = (e) => {
        const rawValue = e.target.value;
        const cleanedValue = rawValue.replace(/\s+/g, ''); // 去除所有空白字符（空格、\t、\n等）
        this.form.setFieldsValue({jhid: cleanedValue}); // 更新表单值
    }

    render() {
        const required = {required: true, message: "此为必填项"}
        const idCheck = {pattern: /^\d{19}$/, message: '必须是19位数字'}
        return (<Modal
            title={this.state.title}
            visible={this.state.visible}
            // onOk={this.handleOk}
            onCancel={this.handleCancel}
            maskClosable={false}
            footer={this.state.handler === "view" ? null : [
                <Button onClick={this.handleCancel}>取消</Button>,
                <ButtonLock onClick={this.handleOk} type="primary">确定</ButtonLock>
            ]}
        >
            <Form ref={form => this.form = form}>
                <Row>
                    <Col span={24}>
                        <Form.Item label="计划id" name="jhid" rules={[required, idCheck]}>
                            <Input allowClear placeholder="输入计划id" onBlur={this.idBlur}></Input>
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item label="计划名称" name="jhmc" rules={[required]}>
                            <Input allowClear placeholder="输入计划名称"></Input>
                        </Form.Item>
                    </Col>
                    <SelectJhAccount
                        colSpan={24}
                        rules={[required]}
                        label="账号名称"
                        onFormChange={this.onFormChange}
                        keyword="zhid"
                        key="zhid"/>
                    <SelectState2 colSpan={24} defaultValue={1}></SelectState2>
                </Row>
            </Form>
        </Modal>)
    }
}

export default AddOrEdit;